package com.nwpu.bigdata.service.impl;

import java.util.ArrayList;

import java.util.List;

import com.nwpu.bigdata.model.User;
import com.nwpu.bigdata.service.LogMysqlService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.nwpu.bigdata.dao.mapper.ExceptLogMapper;
import com.nwpu.bigdata.dto.BackendResult;
import com.nwpu.bigdata.model.ExceptLog;
import com.nwpu.bigdata.model.ExceptLogExample;

/**
 * @author carlin
 */
@Service
public class LogMysqlServiceImpl implements LogMysqlService {
	private static final Long PAGE_SIZE = 15L;
	private static Logger logger = LoggerFactory.getLogger(LogMysqlServiceImpl.class);

	@Autowired
	private ExceptLogMapper exceptLogMapper;

	@Override
	public BackendResult<List<ExceptLog>> selectAllLog() {
		ArrayList<ExceptLog> exceptLogs = exceptLogMapper.selectAll();
		if(exceptLogs.size() == 0 || exceptLogs == null) {
			return new BackendResult<>(false, "No exception log in database!");
		}
		
		logger.debug("get all logs in mysql. numbers: {}.",exceptLogs.size());
		return new BackendResult<>(true, exceptLogs);
	}

	@Override
	public  BackendResult<List<ExceptLog>> selectByExample(ExceptLogExample example) throws Exception {
		return null;
	}

	@Override
	public BackendResult<List<ExceptLog>> selectLogByPage(String userName, Long page) {
		Long low = (page - 1) * PAGE_SIZE;
		List<ExceptLog> exceptLogs = exceptLogMapper.selectLogByPage(userName, low, PAGE_SIZE);
		if(exceptLogs == null) {
			logger.error("the page {} error, no full log info !", page);
			return new BackendResult<>(false, "the page error, no full log info !");
		}else {
			logger.info("the page {} has {} log info !", exceptLogs.size());
			return new BackendResult<List<ExceptLog>>(true,exceptLogs);
		}
	}

	@Override
	public long countExceptLog(User user) {
		ExceptLogExample exceptLogExample = new ExceptLogExample();
		ExceptLogExample.Criteria criteria = exceptLogExample.createCriteria();
		criteria.andUserEqualTo(user.getUsername());
		return exceptLogMapper.countByExample(exceptLogExample);
	}

}
